package com.ybg.share.core.dbapi.dao.sql;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.sql.PagerUtils;
import com.alibaba.druid.util.JdbcConstants;
import com.ybg.share.core.remoteapi.dto.FinancialDTO;
import org.apache.ibatis.annotations.Param;

public class ShareFinancialSQL {

    public String getFinancialOfQuarterByPage(@Param("dto") FinancialDTO dto){
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT id,report_date,stock_id,code,basic_eps,eps,cash_flow,revenue,profitability,");
        sb.append("operating_profit,investment_return,non_operating_income,total_profit,net_profit,");
        sb.append("deduct_profit,net_cash_flow,net_increase_cash,total_assets,current_assets,total_liabilities,");
        sb.append("current_liabilities,stockholder_equity,weighted_return_equity,market ");
        sb.append("FROM share_financial_quarter WHERE 1=1");
        getWhereString(sb,dto);
        return PagerUtils.limit(sb.toString(), JdbcConstants.MYSQL,dto.getOffset().intValue(),dto.getSize().intValue());
    }

    public String getFinancialOfYearByPage(@Param("dto") FinancialDTO dto){
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT id,report_date,stock_id,code,basic_eps,eps,cash_flow,revenue,profitability,");
        sb.append("operating_profit,investment_return,non_operating_income,total_profit,net_profit,deduct_profit,");
        sb.append("net_cash_flow,net_increase_cash,total_assets,current_assets,total_liabilities,");
        sb.append("current_liabilities,stockholder_equity,weighted_return_equity,market ");
        sb.append("FROM share_financial_year WHERE 1=1 ");
        getWhereString(sb,dto);
        return PagerUtils.limit(sb.toString(), JdbcConstants.MYSQL,dto.getOffset().intValue(),dto.getSize().intValue());
    }

    public String countQuarter(@Param("dto") FinancialDTO dto){
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT COUNT(id) ");
        sb.append("FROM share_financial_quarter WHERE 1=1 ");
        getWhereString(sb,dto);
        return PagerUtils.count(sb.toString(), JdbcConstants.MYSQL);
    }

    public String countYear(@Param("dto") FinancialDTO dto){
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT COUNT(id) ");
        sb.append("FROM share_financial_year WHERE 1=1 ");
        getWhereString(sb,dto);
        return PagerUtils.count(sb.toString(), JdbcConstants.MYSQL);
    }

    private void getWhereString(StringBuilder sb,FinancialDTO dto){
        if (StrUtil.isNotBlank(dto.getCode())){
            sb.append(" AND code = #{dto.code}");
        }
        if (StrUtil.isNotBlank(dto.getMarket())){
            sb.append(" AND code = #{dto.market}");
        }
        if (StrUtil.isNotBlank(dto.getReportDate())){
            sb.append(" AND code = #{dto.reportDate}");
        }
        if (null != dto.getStockId()){
            sb.append(" AND code = #{dto.stockId}");
        }
    }
}
